<?php
namespace backend\controllers\base;

use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;

class BaseController extends Controller
{
    public $EBusinessID='1283287';
    public $AppKey='55ad180d-29cb-4e14-bd78-8cea411eacfd';
    public $ReqURL='http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';
    /**
     * 单张图片上传及多张图片上传
     * 
     * @param type $model
     *            model实例
     * @param type $rootPath
     *            保存路径
     * @param type $randName
     *            保存图片名
     * @param type $pk
     *            图片保存所属字段
     * @return string 图片名
     */
    public function upload($model, $name, $pk, $size = [], $array = false, $rootPath = false, $randName = false)
    {
        if (! $rootPath)
            $rootPath = $path = "uploads/{$name}/logo/" . date('Y-m-d') . '/';
        if (! empty($size)) {
            $rootPath .= 'big/';
            foreach ($size as $key => $val) { // 批量循环创建文件夹
                $mkpath = $path . $key;
                $this->makedir($mkpath);
            }
        }
        $this->makedir($rootPath);
        if ($array) { // 判断是否多图上传
            $file = UploadedFile::getInstances($model, $pk);
            if (! empty($file)) {
                $filenames = [];
                foreach ($file as $val) {
                    $ext = $val->getExtension();
                    $randName = time() . rand(1, 9999);
                    $filename = $randName . '.' . $ext;
                    $filepath = $rootPath . $filename;
                    if ($val->saveAs($filepath)){
                        $filepath = $this->setImageSize($filepath, $path, $size, $filename); // 按照尺寸批量缩放图片
                        $filenames[] = [
                            'id' => null,
                            'name' => '/' . $filepath,
                            'pid' => $array
                        ];
                    }
                }
                return $filenames; // 返回上传成功图片数组
            }
        } else {
            if (! $randName)
                $randName = time() . rand(1, 9999);
            $file = UploadedFile::getInstance($model, $pk);
            if($file){
                $ext = $file->getExtension();
                $filename = $randName . '.' . $ext;
                $filepath = $rootPath . $filename;
                if($file->saveAs($filepath)){

                $filepath = $this->setImageSize($filepath, $path, $size, $filename); // 按照尺寸批量缩放图片
		}
            }
            return $filepath; // 返回图片路径
        }
    }

    public function actions()
    {
        parent::actions();
        return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imagePathFormat" => "/uploads/" . \Yii::$app->controller->id . "/{yyyy}{mm}{dd}/{time}{rand:6}"
                ] // 上传保存路径

            ]
        ];
    }
    public function curl($url,$post){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    public function sendCode($tel,$content){
        $url='https://api.miaodiyun.com/20150822/industrySMS/sendSMS';
        $time=date('YmdHis');
        $sid='a6e4f21a2b5d4ee49b449dede7a3d122';
        $token='9832d34754b3483ebe7f9765ef4c073f';
        $code=rand(100000, 999999);
        $data=[
            'accountSid'=>$sid,
            'smsContent'=>$content,
            'to'=>$tel,
            'timestamp'=>$time,
            'sig'=>md5($sid.$token.$time),
            'respDataType'=>'JSON'];
        $json=$this->curl($url, $data);
        $json=json_decode($json,true);
        if($json['respCode']=='00000'){
            return true;
        }
        return $json['respCode'];
    }
    /**
     * 批量插入数据
     * 
     * @param type $model            
     * @param type $items            
     * @return boolean
     */
    public function insertAll($model, $items)
    {
        return Yii::$app->db->createCommand()
            ->batchInsert($model->tableName(), $model->attributes(), $items)
            ->execute();
    }
    // 无限极分类重组
    public function dataSort($data, $pid = 'pid')
    {
        $list = [];
        if (! empty($data)) {
            foreach ($data as $val) {
                $list[$val[$pid]][] = $val;
            }
        }
        return $list;
    }

    /**
     * 批量压缩图片
     * 
     * @param string $file
     *            图片路径
     * @param string $path
     *            文件夹路径
     * @param array $data
     *            压缩尺寸数组
     * @param string $filename
     *            文件名
     */
    public function setImageSize($file, $path, $data, $filename)
    {
        if (! empty($data)) {
            $size = GetImageSize($file);
            switch ($size[2]) {
                case 1:
                    $im_in = imagecreatefromgif($file);
                    break;
                case 2:
                    $im_in = imagecreatefromjpeg($file);
                    break;
                case 3:
                    $im_in = imagecreatefrompng($file);
                    break;
            }
            foreach ($data as $key => $val) {
                $newfile = $path . $key . '/' . $filename;
                if ($size[0] > $val) {
                    $height = $size[1] * ($val / $size[0]);
                    $im_out = ImageCreateTrueColor($val, $height);
                    /* ImageCopyResized */
                    imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $val, $height, $size[0], $size[1]);
                    Imagejpeg($im_out, $newfile);
                    chmod($newfile, 0777);
                    ImageDestroy($im_out);
                } else {
                    copy($file, $newfile);
                }
            }
            return $newfile;
            ImageDestroy($im_in);
        }
        return $file;
    }

    /**
     * 创建文件夹
     * 
     * @param string $path
     *            文件夹路径
     */
    public function makedir($path)
    {
        if (! file_exists($path)) {
            mkdir($path, 0777, true);
        }
    }
    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($type,$num){
        $requestData= "{'OrderCode':'','ShipperCode':'{$type}','LogisticCode':'{$num}'}";
    
        $datas = array(
            'EBusinessID' => $this->EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $this->AppKey);
        $result=$this->sendPost($this->ReqURL, $datas);
    
        //根据公司业务处理返回的信息......
    
        return $result;
    }
    
    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);
    
        return $gets;
    }
    
    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
}
